import { Context, Next } from "koa";
import Router from "koa-router";
import fetch from "../utils/request";

const proxyRouter = new Router({ prefix: "/proxy_api" });
// { prefix: "/" }

proxyRouter.get("/lao", async (ctx: Context, next: Next) => {
  const { request } = ctx;
  const { body, query, headers } = request;
  const { proxy_url } = headers;

  if (!proxy_url) {
    ctx.body = {
      code: 400,
      msg: "headers 中缺少proxy_url字段",
    };
    return;
  }
  const res = await fetch({
    params: query || {},
    url: proxy_url as string,
    headers,
  });

  ctx.body = res;
});

proxyRouter.post("/lao", async (ctx: Context, next: Next) => {
  const { request } = ctx;
  const { body, headers } = request;
  const { proxy_url } = headers;
  if (!proxy_url) {
    ctx.body = {
      code: 400,
      msg: "headers 中缺少proxy_url字段",
    };
    return;
  }
  const res = await fetch({
    data: body || {},
    method: "POST",
    url: proxy_url as string,
    headers,
  });
  ctx.body = res;
});

export default proxyRouter;
